﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mimoza.AgentLayer.Communication;
using Mimoza.Transport;
using System.Xml.Serialization;

namespace Mimoza.ServiceLayer
{
    /// <summary>
    /// Class for accept connection from host to server. 
    /// Send intiate connection signal to host.
    /// </summary>
    public class HostsConnections : BaseObject
    {
        public HostsConnections(Configuration config)
            : base(config)
        {
            RequestSignalHostConnection.RegisterInTransport();
            ReplyHostConnection.RegisterInTransport();

            RequestHostConnection.RegisterHandler(
                new RequestHostConnection.Handler(
                    ProcessHostConnectionRequest));
        }

        public void SendInitiateConnectionSignal(string toHostId,
            string hostAddr, int hostPort)
        {
            Common.Logger.Log.Info("HostsConnections.SendInitiateConnectionSignal id - '" +
                toHostId + "' address - '" + hostAddr + "' upd port - " +
                hostPort.ToString() + "'.");

            if (hostAddr != null)
            {
                RequestSignalHostConnection request = new RequestSignalHostConnection();
                request.ToHostId = toHostId;

                Connection updConn = Transport.Transport.CreateUDPConnection(hostAddr, hostPort);
                updConn.SendRequest(request);
                updConn.Close();
            }
        }

        ReplyHostConnection ProcessHostConnectionRequest(RequestHostConnection request)
        {
            Common.Logger.Log.Info("ProcessHostConnectionRequest host: id - '"
                + request.HostId + "'.");

            ReplyHostConnection reply = new ReplyHostConnection();
            reply.HostId = "";

            if (CheckHostId(request.HostId))
            {
                reply.HostId = request.HostId;
            }

            return reply;
        }

        bool CheckHostId(string hostId)
        {
            Common.Logger.Log.Info("CheckHostId host: id - '"
                + hostId + "'.");

            return true;
        }
    }
}
